const http = require("http");
const fs = require("fs")
const url = require("url")
const qs = require("querystring")

http.createServer((req, res)=>{
    if(req.url !== "/favicon.ico"){
        if(url.parse(req.url).pathname === "/api"){
            ajaxHandle(req, res)
        }else{    
            fileHandle(req, res)
        }
    }
}).listen("3000");

function ajaxHandle(req, res){
    let urlObj = url.parse(req.url, true); 
    let str = "";
    req.on("data",(d)=>{
        str += d;
    })
    req.on("end",()=>{
        // console.log(str);
        let reqData;
        if(str === ""){
            reqData = urlObj.query;
        }else{
            reqData = qs.parse(str);
        }
        console.log(reqData);

        res.end();
    })
}

function fileHandle(req, res){
    console.log(url.parse(req.url))
    fs.readFile("./pdt"+url.parse(req.url).pathname,(err,data)=>{
        if(err){
            console.log("./pdt"+url.parse(req.url).pathname);
            res.write("404");
        }else{
            res.write(data);
        }
        res.end();
    })
}